import java.io.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

//扫描指定目录，并找到文件名称或者文件内容中包含指定字符的所有普通文件（不包含目录）
public class Demo3 {
    public static void main(String[] args) throws IOException {
        Scanner scanner = new Scanner(System.in);
        System.out.println("输入要扫描的根目录(绝对路径OR相对路径): ");
        String rootDirectoryPath = scanner.next();

        File rootDirectory = new File(rootDirectoryPath);
        if (!rootDirectory.isDirectory()) {
            System.out.println("您输入的根目录不存在或者不是目录，退出");
        }

        System.out.println("请输入要找出查询的字符: ");
        String token = scanner.next();

        List<File> result = new ArrayList<>();
        scanDirectory(rootDirectory, token, result);
        System.out.println("找到了符合条件的文件一共" + result.size() + "个,它们分别是:");
        for (File file : result) {
            System.out.println(file.getCanonicalPath());
        }
    }

    private static void scanDirectory(File rootDirectory, String token, List<File> result) {
        File[] files = rootDirectory.listFiles();

        if (files == null || files.length == 0) {
            return;
        }

        for (File file : files) {
            if (file.isDirectory()) {
                scanDirectory(file, token, result);
            } else {
                if (isContentContains(file, token)) {
                    result.add(file.getAbsoluteFile());
                }
            }
        }

    }

    private static boolean isContentContains(File file, String token) {
        if (file.getName().contains(token)) {
            return true;
        }

        StringBuilder stringBuilder = new StringBuilder();
        try (InputStream inputStream = new FileInputStream(file);
             Scanner scanner = new Scanner(inputStream, "UTF-8")) {
            while (scanner.hasNextLine()) {
                stringBuilder.append(scanner.nextLine());
                stringBuilder.append("\r\n");
            }
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        if (stringBuilder.indexOf(token) != -1) {
            return true;
        }

        return false;
    }
}
